$(function(){

	$.validator.addMethod(
		"validateRoom",
		function(value, element, param) {
			return validateRoom();
		},
		'请选择有效的房间' //验证信息
	);

	$("#addForm").validate({
		ignore: "",
		rules: {
			link: {required:true, url:true},
			positionCode: 'required',
			advImg: 'required',
			roomName: {validateRoom: true}
		},
		messages: {
			link: {
				required: "请输入链接地址"
			},
			positionCode: {
				required: "请选择展示位置"
			},
			advImg: {
				required: "请选择广告图片"
			},
			roomName: {
				required: "请选择有效的房间"
			}
		}
	});

	// 初始化上传组件
	$('#fileupload').fileupload({
		dataType : 'json',
		done : function(e, data) {
			if (data.result.status == 'ok') {
				$('#js_advImg').val(data.result.url);
				$('#preview').attr('src', data.result.url);
			}
		}
	});

	// 自动提示选择房间id
	$("#js_roomName").autocomplete({
		source: function(request, response) {
			var roomName = $("#js_roomName").val();
			if(!roomName || $.trim(roomName) == '') {
				return false;
			}

			$.ajax({
				url: "/api/room/autocomplete/" + roomName,
				dataType: "json",
				success: function(data) {
					response($.map(data.rooms, function(item) {
						return {
							label: item.name,
							value: item.name,
							id: item.id
						}
					}));
				}
			});
		},
		select: function(e, ui) {
			$("#js_roomId").val(ui.item.id)
		},
		delay: 500,
		minLength: 1
	});

	/**
	 * 校验房间id是否有效
	 * 如果房间名为空，则校验通过
	 * 如果房间名不空，但是房间ID为空，则校验不通过
	 * 如果房间名和房间id不为空，但是房间名查询出来的房间id和表单房间id不对应，则校验不通过
	 * 校验使用，所以该方法的ajax请求设置同步
	 * @returns {boolean}
	 */
	function validateRoom() {
		var roomId = $('#js_roomId').val();
		var roomName = $.trim($('#js_roomName').val());
		if (roomName == '') {
			$('#js_roomId').val('');
			return true;
		}

		if ($.trim(roomId.toString()) == '') {
			return false;
		}

		var validateResult = false;
		$.ajax({
			url: "/room/findByName?roomName=" + roomName,
			dataType: "json",
			async: false,
			success: function(data) {
				if(data.status == "ok"){
					var room = data.room;

					if (roomId == room.id) {
						validateResult = true;
					}
				}
			}
		});

		return validateResult;
	}

});